<?php

namespace app\popo\model;

use app\support\JwtHelper;
use support\Model;

class BaseModel extends Model
{
    protected $connection = "mysql";
    public const UPDATED_AT = "update_time";
    public const CREATED_AT = "create_time";
    public const CREATE_USER = "create_user";
    public const UPDATE_USER = "update_user";

    protected bool $auto_fill_create_user = false;
    protected bool $auto_fill_update_user = false;


    public function saveByDto(): void
    {
        $attributes = [];
        if ($this->auto_fill_create_user) {
            $attributes[self::CREATE_USER] = JwtHelper::getEmployee()->id;
        }
        if ($this->auto_fill_update_user) {
            $attributes[self::UPDATE_USER] = JwtHelper::getEmployee()->id;
        }
        foreach ($this->attributes as $key => $value) {
            $attributes[$this->camelToSnake($key)] = $value;
        }

        $this->attributes = $attributes;
        $this->save();
    }

    public function toViewData(): array
    {
        $data = $this->toArray();
        $item = array();
        foreach ($data as $key => $value)
        {
            $key = $this->snakeToCamel($key);
            $item[$key] = $value;
        }

        return $item;
    }

    public function updateWith(array $data): bool
    {
        if ($this->auto_fill_update_user) {
            $data[self::UPDATE_USER] = JwtHelper::getEmployee()->id;
        }
        $item = array();
        foreach ($data as $key => $value) {
            $item[$this->camelToSnake($key)] = $value;
        }
        return $this->update($item);
    }

    // 定义一个方法来转换属性名
    public function convertCamelToSnake()
    {
        $attributes = [];
        foreach ($this->attributes as $key => $value) {
            $attributes[$this->camelToSnake($key)] = $value;
        }

        return $attributes;
    }

    // 驼峰转下划线的辅助方法
    private function camelToSnake($input)
    {
        preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
        $ret = $matches[0];
        foreach ($ret as &$match) {
            $match = $match == strtoupper($match)? strtolower($match) : lcfirst($match);
        }

        return implode('_', $ret);
    }

    private function snakeToCamel($input)
    {
        return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $input))));
    }
}